﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace OP.XmlPrettifier
{
    class Program
    {
        static int Main(string[] args)
        {
            Console.WriteLine("OP.XmlPretifier v" + typeof(Program).Assembly.GetName().Version);
            Console.WriteLine("");
            if (args.Length == 0)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine(" OP.XmlPretifier <inputfile> [outputfile]");
                return 2;
            }
            try
            {
                TextWriter txtWriter;
                if (args.Length == 1)
                    txtWriter = Console.Out;
                else
                    txtWriter = new StreamWriter(args[1]);

                XmlReaderSettings rSettings = new XmlReaderSettings();
                rSettings.ConformanceLevel = ConformanceLevel.Fragment;
                rSettings.CloseInput = true;

                XmlWriterSettings wSettings = new XmlWriterSettings();
                wSettings.OmitXmlDeclaration = true;
                wSettings.CloseOutput = false;
                wSettings.Indent = true;
                wSettings.IndentChars = "    ";
                wSettings.NewLineOnAttributes = false;
                wSettings.NewLineChars = Environment.NewLine;
                wSettings.NewLineHandling = NewLineHandling.Replace;

                using (XmlReader reader = XmlReader.Create(args[0], rSettings))
                {
                        while (reader.Read())
                        {
                            if (reader.NodeType == XmlNodeType.XmlDeclaration)
                                continue;
                            using (XmlWriter writer = XmlWriter.Create(txtWriter, wSettings))
                            {
                                XmlReader fragmentReader = reader.ReadSubtree();
                                XmlDocument doc = new XmlDocument();
                                doc.Load(fragmentReader);
                                doc.Save(writer);
                                fragmentReader.Close();
                                txtWriter.WriteLine();
                            }
                            reader.Skip();
                        }

                }
                return 0;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("An error occured while trying to pretify the Xml file: " + args[0]);
                Console.Error.WriteLine("Error: ");
                Console.Error.WriteLine(ex.ToString());
                return 1;
            }

        }
    }
}
